package com.memorywords.controller;

import com.memorywords.pojo.Result;
import com.memorywords.pojo.User;
import com.memorywords.service.UserService;
import com.memorywords.utils.JwtUtil;
import com.memorywords.utils.Md5Util;
import com.memorywords.utils.RandomStringUtil;
import com.memorywords.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        String email = params.get("email");
        //校验数据格式
        User user = userService.findByUserName(username);
        if (user == null) {
            //注册
            userService.register(username, password, email);
            return Result.success();
        }else{
            return Result.error(1005, "用户名被占用");
        }
    }


    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{1,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
        User user = userService.findByUserName(username);
        if (user == null) {
            return Result.error(1002, "用户名错误");
        }
        if(Md5Util.getMD5String(password).equals(user.getPassword())){
            //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("userId",user.getUserId());
            claims.put("username",user.getUsername());
            String token = JwtUtil.genToken(claims);

            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set(token,token, 1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error(1002,"密码错误");
    }

    @PostMapping("/editPwd")
    public Result exitPwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token){
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");

        if(!StringUtils.hasLength(oldPassword) || !StringUtils.hasLength(newPassword)){
            return Result.error(1004, "缺少必填项");
        }

        //原密码是否正确

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPassword))){
            return Result.error(1002, "原密码不正确");
        }

        //密码更新
        userService.exitPwd(newPassword);

        //删除token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);

        return Result.success();
    }

    @PostMapping("/getEmail")
    public Result getEmail(String email, @RequestHeader("Authorization") String token) {

        String code = RandomStringUtil.randomNumeric(6);
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if(!loginUser.getEmail().equals(email)){
            return Result.error(1002, "邮箱不正确");
        }

        log.info(code);
        //存储验证码
        stringRedisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);

        userService.getEmail(email, code);

        return Result.success();
    }

    @PostMapping("/editPwdByEmail")
    public Result exitPwdByEmail(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token){
        String emailKey = params.get("emailKey");
        String newPassword = params.get("newPassword");

        if(!StringUtils.hasLength(emailKey) || !StringUtils.hasLength(newPassword)){
            return Result.error(1004, "缺少必填项");
        }

        //是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        String email = loginUser.getEmail();
        String realKey = stringRedisTemplate.opsForValue().get(email);
        if (realKey == null) {
            return Result.error(1005, "邮箱为空");
        }
        if(!realKey.equals(emailKey)){
            return Result.error(1002, "验证码错误");
        }

        //密码更新
        userService.exitPwd(newPassword);
        //删除token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);

        return Result.success();
    }

    @PostMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token){
        //删除token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return Result.success();
    }

    @PatchMapping("/updateProgress")
    public Result updateProgress(@RequestHeader("Authorization") String token, int addWords){
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        int progress = loginUser.getProgress() + addWords;
        int id = loginUser.getUserId();
        userService.updatePgs(progress, id);
        return Result.success();
    }

    @GetMapping("/look")
    public Result look(@RequestHeader("Authorization") String token){
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        int progress = loginUser.getProgress();
        return Result.success(progress);
    }

}
